package domain.util;

import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

import domain.Resource;

public class MarcFormData {

	public static Resource getData(Map<String, String[]> parameters) {

		Resource result = new Resource();
		
		String[] s = parameters.get("docType");
		result.setType(getTypeResource(s[0]));
		
		Map<String, MarcLine> marcCode = new TreeMap<String, MarcLine>();
		
		for (String param : parameters.keySet()) {
			
			if (parameters.get(param)[0].trim().equals(""))
				continue;
			if (!param.startsWith("tag"))
				continue;
			if (param.contains("code"))
				continue;
			
			String[] split = param.split("\\Q_\\E");
			
			if (!marcCode.containsKey(split[1]))
				marcCode.put(split[1], new MarcLine(split[1]));
			
			MarcLine line = marcCode.get(split[1]);
			line.alter(split[2], split[Math.min(split.length - 1, 3)], parameters.get(param)[0]);
		}
		
		marcToSimple(result, marcCode);
		
		return result;

	}
	
	public static void simpleToMarc(Resource r) {
		
	}
	
	public static void marcToSimple(Resource r, Map<String, MarcLine> marcCode) {
		
		String code = "";
		for (String tag : marcCode.keySet()) {
			MarcLine line = marcCode.get(tag);
			
			for (Subfield sub : line.getSubfields()) {
				alterResourceSubfield(r, sub, tag);
			}
			
			code += "\n" + line.toString();
		}
		
		r.setMarcCode(code.trim());
	}

	private static void alterResourceSubfield(Resource r, Subfield sub, String tag) {
		ParserGenerated.put(r, tag + "$" + sub.getName(), sub.getBody());
	}

	private static TypesResource getTypeResource(String type) {
		if (type.equals("book"))
			return TypesResource.Book;
		else if (type.equals("colArticle"))
			return TypesResource.CollectionArticle;
		else if (type.equals("issue"))
			return TypesResource.Issue;
		else if (type.equals("serial"))
			return TypesResource.Serial;
		else if (type.equals("volume"))
			return TypesResource.Volume;
		else if (type.equals("article"))
			return TypesResource.Article;
		else if (type.equals("technicalReport"))
			return TypesResource.TechnicalReport;
		else if (type.equals("thesis"))
			return TypesResource.Thesis;
		else 
			return TypesResource.Other;
	}

}
